package demo1;

import java.util.Arrays;

//大根堆
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }
    //向下调整
    private void shiftDown (int parent, int len) {
        int child = 2 * parent + 1;
        //1.最起码 是有左孩子的, 至少有1个孩子
        while (child < len) {
            if (child + 1 < len && elem[child] < elem[child + 1]) {
                child++; //保证当前左右孩子最大值的下标
            }
            if (elem[child] > elem[parent]) {
                int temp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = temp;
            } else {
                return; //孩子节点小于等于父节点 退出函数
            }
            parent = child;
            child = 2 * parent + 1;
        }
    }
    //创建堆
    public void creatHeap (int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
        for (int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            //调整
            shiftDown(parent,usedSize);
        }
    }
    //向上调整
    private void shiftUp (int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (this.elem[parent] < this.elem[child]) {
                int temp = this.elem[child];
                this.elem[child] = this.elem[parent];
                this.elem[parent] = temp;
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }
    //入队列
    public void offer (int val) {
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem,this.elem.length*2);
        }
        this.elem[usedSize++] = val;
        //注意这里传入的是usedSize - 1
        shiftUp(usedSize - 1);
    }
    //出队列
    public int poll () {
        if (isEmpty()) {
            throw new RuntimeException("优先级队列为空!");
        }
        //第一个数  与 最后一个数 交换
        int temp = this.elem[0];
        this.elem[0] = this.elem[usedSize - 1];
        this.elem[usedSize - 1] = temp;
        //有效数减一
        usedSize--;
        //向下调整
        shiftDown(0,usedSize);
        return temp;
    }

    //堆排序  从小到大
    public void heapSort () {
        int end = usedSize - 1;
        while (end != 0) {
            int temp = this.elem[0];
            this.elem[0] = this.elem[end];
            this.elem[end] = temp;
            shiftDown(0,end);
            end--;
        }
    }
    //判断数组是否满
    public boolean isFull () {
        return usedSize == this.elem.length;
    }
    public boolean isEmpty () {
        return usedSize == 0;
    }

}
